<?php
App::uses('AppController', 'Controller');

class SearchController extends AppController {
	var $name = 'Search';
	var $uses=array('Search','Film','Tags','Actor','Director');
	
	public function Search(){
	
		if ($this->request->is('post') || $this->request->is('put')) {
			//$condition=array('Titulo'=>$this->request->data['Film']$this->request->data['Film']
			//var_dump($this->request->data['Film']);
			//var_dump($this->request->data['Actor']);
			
			$titulo= empty($this->request->data['Film']['title'])? null:$this->request->data['Film']['title'];
			$calificacion= empty($this->request->data['Film']['Calificacion'])?null:$this->request->data['Film']['Calificacion'];
			$actor= empty($this->request->data['Actor'])? null:$this->request->data['Actor'];
			$director= empty($this->request->data['Director'])? null:$this->request->data['Director'];
			//var_dump($actor['Actor']);
			$films=$actors=$directors=null;
			if(!empty($titulo))
				$films=$this->paginate('Film',array('title'=>$titulo));
			if(!empty($actor)){
				foreach($actor['Actor'] as $a){
				
					$actors=$this->paginate('Actor',array('id'=>$a));
				}
			}
			if(!empty($director)){
				foreach($director['Director'] as $a){
				
					$directors=$this->paginate('Director',array('id'=>$a));
				}
			}
			$this->view='index';
			//$this->Film->recursive=1;
			
			$this->set(compact('films','actors','directors'));				
		}else{ // muestro el formulario de busqueda
			$actors = $this->Film->Actor->find('list');
			$directors = $this->Film->Director->find('list');
			$this->set(compact('actors', 'directors'));
		}
	}
	
	public function buscar(){
		if ($this->request->is('post')) {
			$this->view='index';
			$search=strtolower($this->request->data['search']);
			$data=$this->Film->find('all',array('recursive'=>'0','joins' => array(
										array('alias' => 'Tag','table' => 'tags', 'type' => 'LEFT','conditions' => '`Film`.`id` = `Tag`.`film_id`'),
										array('alias' => 'F_A','table' => 'films_actors', 'type' => 'LEFT','conditions' => '`Film`.`id` = `F_A`.`film_id`'),
										array('alias' => 'Actor','table' => 'actors', 'type' => 'LEFT','conditions' => '`F_A`.`actor_id` = `Actor`.`id`'),
										array('alias' => 'F_D','table' => 'films_directors', 'type' => 'LEFT','conditions' => '`Film`.`id` = `F_D`.`film_id`'),
										array('alias' => 'Director','table' => 'directors', 'type' => 'LEFT','conditions' => '`F_D`.`director_id` = `Director`.`id`')																	
										),'conditions' => array('or'=>array('LOWER(title)' => $search,'LOWER(Tag.tag)'=>$search,'LOWER(Actor.name)'=>$search,'LOWER(Director.name)'=>$search)),
										'group'=>'title'
										));
			$this->set('films',$data);;		
		}else
			$this->redirect(array('action' => 'Search'));
	}
}

?>